package com.maiji.cloud.configSecurity;

import com.maiji.cloud.entities.manager.Menu;
import com.maiji.cloud.entities.manager.Role;
import com.maiji.cloud.mapper.MenuMapper;
import com.maiji.cloud.service.MenuService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import java.util.Collection;
import java.util.List;
import java.util.stream.Collectors;

@Component
public class MyMetadataSource implements FilterInvocationSecurityMetadataSource {

    @Autowired
    MenuMapper menuMapper;
    AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Collection<ConfigAttribute> getAttributes(Object obj) {
        String requestUrl = ((FilterInvocation) obj).getRequestUrl();
        List<Menu> allMenus = menuMapper.getAllMenus();
        for (Menu menu : allMenus) {
            if (antPathMatcher.match(menu.getUrl(), requestUrl) && menu.getRoles().size()>0) {
                List<String> roles = menu.getRoles().stream().map(Role::getName).collect(Collectors.toList());
                String[] roleArr = new String[roles.size()];
                return SecurityConfig.createList(roles.toArray(roleArr));
            }
        }
        //没有匹配上的资源，都是登录访问
        return SecurityConfig.createList("系统管理员");
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return null;
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return FilterInvocation.class.isAssignableFrom(aClass);
    }

}
